/**
 * Created by Administrator on 2015/12/3.
 */
define("wangwu/ceshi/D3Test",
    [
        'dojo/_base/declare',
        'dojo/_base/lang',
        'dojo/on',
        'dojo/dom-construct',
        'dojo/query',

        'esri/layers/GraphicsLayer',

        'd3/d3'

    ],function(declare,lang, on,domConstruct,djQuery,
               GraphicsLayer,
               D3){
        var d = declare(null,{
            constructor:function(map,opt){
                this.map = map;
                this.option = {
                    rectRadius:5,//Բ��
                    rectWidth:150,//���ο��
                    rectOffsetX:0,//����������xƫ��
                    rectOffsetY:10,//����top yƫ��
                    rectFillColor:'rgba(144,155,165,0.6)',//���������ɫ
                    rectFillHighlightColor:'rgba(20,20,220,0.8)',/////////////
                    rectStrokeColor:'rgba(33,33,33,0.2)',//���������ɫ
                    rectStrokeHighlightColor:'rgba(20,20,20,1)',
                    rectStrokeWidth:1,//���������
                    labelVerticalAlign:4,//��ǩ��ֱ���
                    labelsPaddingTop:2,//��ǩ�������������ļ��
                    labelsPaddingBottom:2,
                    labelsPaddingLeft:2,
                    labelsPaddingRight:2,
                    fontSize:13,//�����С
                    fontColor:'rgba(255,255,0,1)',
                    tipFillColor:'rgba(255,255,255,1)',
                    tipfontColor:'rgba(0,0,0,1)'
                };
                (opt)?lang.mixin(this.option,opt):0;
                //this.d3Layer =new GraphicsLayer({id:"d3Layer"});
                //this.map.addLayer(this.d3Layer);
                this.initialized = false;

                this.buttonId = 'testDojo-'+parseInt(Math.random()*1000);
                domConstruct.create('div', {
                    'id':'aaaa1111',
                    'style':'position:absolute;right:70px;top:50px;width:100px',
                    'innerHTML':'<input type="button" value="开启" id="'+this.buttonId+'"/>'
                }, map.id);
                var button = djQuery('#'+this.buttonId);
                on(button, 'click', lang.hitch(this, this.drawPie));

                this.buttonId01 = 'testDojo01-'+parseInt(Math.random()*1000);
                domConstruct.create('div', {
                    'id':'aaaa2222',
                    'style':'position:absolute;right:20px;top:50px;width:100px',
                    'innerHTML':'<input type="button" value="清除" id="'+this.buttonId01+'"/>'
                }, map.id);
                var button01 = djQuery('#'+this.buttonId01);
                on(button01, 'click', lang.hitch(this, this.clear));

            },
            //-----------------------public----------------------------
            init:function(){
                if (this.initialized) return;
                this.initialized = true;
                this._init();
            },
            //开启事件侦听
            openEventListen:function(){
                this.pan = on(this.map, 'pan', lang.hitch(this, this._pan));
                this.zoomStart = on(this.map, 'zoom-start', lang.hitch(this, this._zoomStart));
                this.zoomEnd = on(this.map, 'zoom-end', lang.hitch(this, this._zoomEnd));
            },
            //关闭事件侦听
            closeEventListen:function(){
                (this.pan)?this.pan.remove():0;
                (this.zoomStart)?this.zoomStart.remove():0;
                (this.zoomEnd)?this.zoomEnd.remove():0;
            },
            polygon:function(){
                var o = this.option;
                this.node.append('polygon')
                    .attr({
                        //箭头图标
                        "id":"polygon",
                        "points":"165.834,179.084 165.834,166.166 152.917,166.166 179.083,152.917",
                        'fill': "blue",
                        'stroke':"#000000",
                        'stroke-width': 1
                    });
                this.rotate();
            },
            polyline:function(){
                var o = this.option;
                this.node.append('polyline')
                    .attr({
                        "points":"0,0 0,200 200,200 200,400 400,400 400,600",
                        'fill': 'rgba(33,33,33,0)',
                        'stroke': "red",
                        'stroke-width': 2
                    });
                this.rotate();
            },
            rect:function(){
                var o = this.option;
                this.node.append('rect')
                    .attr({
                        "id":"rect",
                        'x': 55,
                        'y': 55,
                        'width': 50,
                        'height': 50,
                        'fill': o.tipFillColor,
                        'stroke': o.rectStrokeColor,
                        'stroke-width': o.rectStrokeWidth,
                        'rx': o.rectRadius,
                        'ry': o.rectRadius
                    });
                this.rotate();
            },
            circle:function(){
                var o = this.option;
                this.node.append('circle')
                    .attr({
                        'cx': 200,
                        'cy': 200,
                        'fill': "red",
                        'stroke': "black",
                        'stroke-width': o.rectStrokeWidth,
                        'r': 100,
                    });
            },
            ellipse:function(){
                var o = this.option;
                this.node.append('ellipse')
                    .attr({
                        "id":"ellipse",
                        'cx': 200,
                        'cy': 200,
                        'fill': o.tipFillColor,
                        'stroke': o.rectStrokeColor,
                        'stroke-width': o.rectStrokeWidth,
                        'rx': 60,
                        'ry':100
                    });
                this.rotate();
            },
            clear:function(){
                this._clear();
            },
            drawPie:function(){
                console.log("点击按钮,drawPie...效果：饼状图pie");

                var dataset = [1,2,3,4,5];
                var pie = D3.layout.pie();//定义一个布局，布局，英文是 Layout。
                var piedata = pie(dataset);//转换后的数据给到piedata，记住布局不是要直接绘图，而是为了得到绘图所需的数据。
                //console.log(piedata);

                var outerRadius = 150; //外半径
                var innerRadius = 0; //内半径，为0则中间没有空白

                var arc = D3.svg.arc()  //弧生成器arc，此时，arc 可以当做一个函数使用，把 piedata 作为参数传入，即可得到路径值。
                    .innerRadius(innerRadius)   //设置内半径
                    .outerRadius(outerRadius);  //设置外半径
                var arcs =  this.svg.selectAll("g")//先在 <svg> 里添加足够数量（5个）个分组元素（g），每一个分组用于存放一段弧的相关元素。
                    .data(piedata)
                    .enter()
                    .append("g")
                    .attr("transform","translate("+ (this.width/2) +","+ (this.width/2) +")");
                var color = D3.scale.category10();   //有十种颜色的颜色比例尺
                arcs.append("path")//每个 <g> 中都有 <path> ,路径值的属性名称是 d
                    .attr("fill",function(d,i){
                        return color(i);
                    })
                    .attr("d",function(d){
                        return arc(d);   //调用弧生成器，得到路径值
                    });
                arcs.append("text")
                    .attr("transform",function(d){
                        return "translate(" + arc.centroid(d) + ")";//arc.centroid(d) 能算出弧线的中心
                    })
                    .attr("text-anchor","middle")
                    .text(function(d){
                        return d.data;//要注意，text() 里返回的是 d.data ，而不是 d 。因为被绑定的数据是对象，里面有 d.startAngle、d.endAngle、d.data 等，其中 d.data 才是转换前的整数的值。
                    });

            },
            draw02:function(){
                console.log("点击按钮,执行draw02。。。效果：移动、动态");
                var svg = D3.select("#conten")
                    .append("svg");
                var circle1 = svg.append("circle")
                    .attr("cx", 100)
                    .attr("cy", 100)
                    .attr("r", 45)
                    .style("fill","green");

                //在1秒（1000毫秒）内将圆心坐标由100变为300
                circle1.transition()
                    .duration(2000)//在2秒（2000毫秒）内
                    .attr("cx", 250)//将圆心坐标由100变为250
                    .style("fill","red")//将颜色从绿色变为红色
                    .attr("r", 25)//将半径从45变成25
                    .ease("bounce");//过渡方式采用bounce（在终点处弹跳几次）

            },
            draw01:function(){
                console.log(" 点击了按钮，执行了draw01。。。效果：坐标、直方图、交互操作");
                var width = 400;
                var height = 400;
                //在 body 里添加一个 SVG 画布
                var svg = D3.select("#conten")
                    .append("svg")
                    .attr("width", width)
                    .attr("height", height);
                //画布周边的空白
                var padding = {left:30, right:30, top:20, bottom:20};
                //定义一个数组
                var dataset = [10, 20, 30, 40, 33, 24, 12, 5];
                //x轴的比例尺（序数比例尺）
                var xScale = D3.scale.ordinal()
                    .domain(D3.range(dataset.length))
                    .rangeRoundBands([0, width - padding.left - padding.right]);
                //y轴的比例尺（线性比例尺）
                var yScale = D3.scale.linear()
                    .domain([0,D3.max(dataset)])
                    .range([height - padding.top - padding.bottom, 0]);
                //定义x轴
                var xAxis = D3.svg.axis()
                    .scale(xScale)
                    .orient("bottom");
                //定义y轴
                var yAxis = D3.svg.axis()
                    .scale(yScale)
                    .orient("left");
                //添加x轴
                svg.append("g")
                    .attr("class","axis")
                    .attr("transform","translate(" + padding.left + "," + (height - padding.bottom) + ")")
                    .call(xAxis);

                //添加y轴
                svg.append("g")
                    .attr("class","axis")
                    .attr("transform","translate(" + padding.left + "," + padding.top + ")")
                    .call(yAxis);
                //矩形之间的空白
                var rectPadding = 4;

                //添加矩形元素
                var rects = svg.selectAll(".MyRect")
                    .data(dataset)
                    .enter()
                    .append("rect")
                    .attr("class","MyRect")
                    .attr("transform","translate(" + padding.left + "," + padding.top + ")")
                    .attr("x", function(d,i){
                        return xScale(i)+rectPadding/2;
                    } )
                    .attr("y",function(d){
                        return yScale(d);
                    })
                    .attr("fill","steelblue")
                    .attr("width", xScale.rangeBand() - rectPadding )
                    .attr("height", function(d){
                        return height - padding.top - padding.bottom - yScale(d);
                    })
                    .attr("fill","steelblue")       //填充颜色不要写在CSS里
                    .on("mouseover",function(d,i){
                        d3.select(this)
                            .attr("fill","yellow");
                    })
                    .on("mouseout",function(d,i){
                        d3.select(this)
                            .transition()
                            .duration(500)
                            .attr("fill","steelblue");
                    });

                //添加文字元素
                var texts = svg.selectAll(".MyText")
                    .data(dataset)
                    .enter()
                    .append("text")
                    .attr("class","MyText")
                    .attr("transform","translate(" + padding.left + "," + padding.top + ")")
                    .attr("x", function(d,i){
                        return xScale(i) + rectPadding/2;
                    } )
                    .attr("y",function(d){
                        var min = yScale.domain()[0];
                        return yScale(min);
                    })
                    .attr("dx",function(){
                        return (xScale.rangeBand() - rectPadding)/2;
                    })
                    .attr("dy",function(d){
                        return 20;
                    })
                    .text(function(d){
                        return d;
                    })
                    .transition()
                    .delay(function(d,i){
                        return i * 200;
                    })
                    .duration(2000)
                    .ease("bounce")
                    .attr("y",function(d){
                        return yScale(d);
                    });

            },
            draw:function(){
                console.log("点击按钮，执行draw...");
                var dataset = [250 , 210 , 170 , 130 , 90];
                var rectHeight = 25;   //每个矩形所占的像素高度(包括空白)
                //定义比例尺
                var linear = D3.scale.linear()
                    .domain([0, D3.max(dataset)])
                    .range([0, 250]);
                var axisX = D3.svg.axis()
                    .scale(linear)      //指定比例尺
                    .orient("bottom")   //指定刻度的方向
                    .ticks(5);          //指定刻度的数量

                var svg = D3.select("#conten")
                    .append("svg");
                svg.append("g")
                    .attr("transform","translate(20,130)")
                    .call(axisX);
                svg.selectAll("rect")
                    .data(dataset)//绑定数组
                    .enter()//指定选择集的enter部分
                    .append("rect")//添加足够数量的矩形元素
                    .attr("x",20)
                    .attr("y",function(d,i){
                        return i * rectHeight;
                    })
                    .attr("width",function(d){
                        return linear(d);
                    })
                    .attr("height",rectHeight-2)
                    .attr("fill","steelblue");
            },
            rotate:function(){
                console.log("点击了开启按钮");
                var $ = function(selector) {
                    return document.querySelector(selector);
                };
                var $css3Transform = function(element, value) {
                    //应用transform属性值
                    var arrPriex = ["O", "Ms", "Moz", "Webkit", ""], length = arrPriex.length;
                    for (var i=0; i < length; i+=1) {
                        element.style[arrPriex[i] + "Transform"] = value;
                    }
                };

                var eleDetail =  $("#matrixDetail"),
                    eleRotate = $("#matrixRotate"),
                    eleBox = $("#matrixBox");
                on(eleRotate,"change", function() {
                    var maxVal = this.getAttribute("max"), minVal = this.getAttribute("min"), value = this.value;
                    var cosVal = Math.cos(this.value * Math.PI / 180);
                    var sinVal = Math.sin(this.value * Math.PI / 180);
                    var valTransform = 'matrix('+ cosVal.toFixed(6) +','+ sinVal.toFixed(6) +','+ (-1 * sinVal).toFixed(6) +','+ cosVal.toFixed(6) +',0,0)';
                    eleDetail.innerHTML = '目前属性值为：' + valTransform;
                    $css3Transform(eleBox, valTransform);
                    this.ww = D3.select('#ellipse');
                    this.ww.attr({
                        'transform':valTransform
                    });
                    //D3.select("#matrixBox")
                    //    .attr({
                    //        'transform':valTransform
                    //    });
                });
            },
            //----------------------private------------------------------
            _init:function(){
                this.domId = 'D3Test-'+parseInt(Math.random()*1000);
                D3.select('#'+this.map.id+'_gc')
                    .append('g')
                    .attr({
                        'id':this.domId
                    });
                this.node = D3.select('#' + this.domId);
                this.node.attr({
                    'transform':D3.select('#'+this.map.id+'_graphics_layer').attr('transform')
                });


                this.width = 400;
                this.height = 400;
                this.svgId = 'svg_'+parseInt(Math.random()*1000);
                //在 div 里添加一个 SVG 画布
                this.svg = D3.select("#conten")
                    .append("svg")
                    .attr('id',this.svgId)
                    .attr("width", this.width)
                    .attr("height", this.height);
                this.openEventListen();
            },
            _clear:function(){
                (djQuery('#'+this.domId+' polygon').length > 0)?dojo.empty(this.domId):0;
                (djQuery('#'+this.domId+' polyline').length > 0)?dojo.empty(this.domId):0;
                (djQuery('#'+this.domId+' rect').length > 0)?dojo.empty(this.domId):0;
                (djQuery('#'+this.domId+' circle').length > 0)?dojo.empty(this.domId):0;
                (djQuery('#'+this.domId+' ellipse').length > 0)?dojo.empty(this.domId):0;
                this.closeEventListen();
                this.initialized = false;
                (djQuery('#'+this.svgId+' g').length > 0)?dojo.empty(this.svgId):0;
            },
            _pan:function(e){
                var dx = e.delta.x;
                var dy = e.delta.y;
                var _dx = this.map.__visibleRect.x+dx;
                var _dy = this.map.__visibleRect.y+dy;
                d3.select('#'+this.domId)
                    .attr({
                        'transform':'matrix(1,0,0,1,'+_dx+','+_dy+')'
                    });
            },
            _zoomStart:function(){
                //this._clear();
            },
            _zoomEnd:function(){
                d3.select('#'+this.domId)
                    .attr({
                        'transform':'matrix(1,0,0,1,0,0)'
                    })
            }
        });
        return d;
})